const db = require('../db')
const { getNowTime, formatTime } = require('../utils')
// 集成log4js日志
const log4js = require('../utils/log4js')
const logger = log4js.getLogger('runtime')

/**
 * 新增登录日志
 * @param {*} req
 * @param {*} res
 * @param {*} options
 */
exports.addLogin_log = (req, res, options) => {
  let username = ''
  let status = options.status || 'online'
  let ip = req.headers.ip || ''
  let create_by = ''
  let create_time = getNowTime()
  let last_update_by = ''
  let last_update_time = getNowTime()

  if (!ip) return

  if (JSON.stringify(req.body) !== '{}') {
    !username && (username = req.body.username)
    !create_by && (create_by = req.body.userId || req.body.id)
    !last_update_by && (last_update_by = req.body.userId || req.body.id)
  }
  if (JSON.stringify(req.params) !== '{}') {
    !username && (username = req.params.username)
    !create_by && (create_by = req.params.userId || req.params.id)
    !last_update_by && (last_update_by = req.params.userId || req.params.id)
  }
  if (req.auth !== undefined && JSON.stringify(req.auth) !== '{}') {
    !username && (username = req.auth.username)
    !create_by && (create_by = req.auth.userId || req.auth.id)
    !last_update_by && (last_update_by = req.auth.userId || req.auth.id)
  }
  if (JSON.stringify(options) !== '{}') {
    !username && (username = options.username)
    !create_by && (create_by = options.userId || options.id)
    !last_update_by && (last_update_by = options.userId || options.id)
  }

  let selectSql = `select * from sys_login_log where ip = ? or create_by = ?`
  db.query(selectSql, [ip, create_by], (err, results) => {
    if (err) return logger.error('查询登录日志失败：' + err)
    if (results.length <= 0) {
      // 插入数据库
      const insertsql = 'insert into sys_login_log set ?'
      db.query(
        insertsql,
        {
          username,
          status,
          ip,
          create_by,
          create_time,
          last_update_by,
          last_update_time
        },
        (err, results) => {
          if (err) return logger.error('新增登录日志失败：' + err)
          logger.info('用户' + username + '登录成功...')
        }
      )
    } else {
      // 修改数据库
      let updateSql = `update sys_login_log set status= '${status}', last_update_by=${last_update_by}, last_update_time='${last_update_time}' where ip = ? or create_by = ?`
      db.query(updateSql, [ip, create_by], (err, results) => {
        if (err) return logger.error('修改登录日志失败：' + err)
        if (results.affectedRows !== 1)
          return logger.error('修改登录日志失败：' + updateSql)
        logger.info('用户' + username + '登录成功...')
      })
    }
  })
}

/**
 * 获取登录日志列表
 * @param {*} req
 * @param {*} res
 */
exports.getLoginLog = (req, res) => {
  // 分页加载
  const page_num = req.query.page_num || 1 //当前的num
  const page_size = req.query.page_size || 10 //当前页的数量
  const username = req.query.username
  const params = [
    (parseInt(page_num) - 1) * parseInt(page_size),
    parseInt(page_size)
  ]
  // 查询
  // const selectSql = `select * from sys_login_log limit ?,?`
  const selectSql =
    `select a.*, b.username as create_user, c.username as last_update_user from sys_login_log as a
    left join sys_user as b on a.create_by = b.id
    left join sys_user as c on a.last_update_by = c.id ` +
    (username ? `where a.username like '%${username}%'` : '') +
    ` limit ?,?`
  const pm_list = new Promise((resolve, reject) => {
    db.query(selectSql, params, (err, results) => {
      if (err) return reject(err)
      results.map((item) => {
        item.create_time = formatTime(item.create_time)
        item.last_update_time = formatTime(item.last_update_time)
      })
      resolve(results)
    })
  })

  // 查询数据库总数
  const totalSql = `select count(*) as total from sys_login_log`
  const pm_total = new Promise((resolve, reject) => {
    db.query(totalSql, (err, results) => {
      if (err) return reject(err)
      resolve(results[0].total)
    })
  })

  Promise.all([pm_list, pm_total])
    .then((result) => {
      res.send({
        status: 0,
        message: '获取登录日志列表成功',
        total: result[1],
        data: result[0] || []
      })
    })
    .catch((err) => {
      res.new_send(err)
    })
}
